<template>
  <div class="pd30 role flex flexjcsb">
    <div class="panelWrap role-main">
      <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
        <div>系统角色管理</div>
      </div>
      <div class="con">
        <div class="con-row flex flexac pl search-box">
          <div class="flex flexac">
            <el-input v-if="activeName === '0'" v-model="param.name" class="role-input" placeholder="请输入角色名称..." @input="getFuncRoles" />
            <el-input v-if="activeName === '1'" v-model="param.name" class="role-input" placeholder="请输入角色名称..." @input="getDataRoles" />
          </div>
          <div class="groupbtn flex m-l-40 ">
            <el-button v-if="activeName === '0'" class="flex flexac m-r-20 fs14" size="small" type="warning" @click="getFuncRoles"><i class="co-i" /><span class="search1">查 询</span></el-button>
            <el-button v-if="activeName === '1'" class="flex flexac m-r-20 fs14" size="small" type="warning" @click="getDataRoles"><i class="co-i" /><span class="search1">查 询</span></el-button>
            <el-button class="flexcenter co-empty m-l-25" type="info" @click="handleEmptySearch"><i class="iconfont icon-qingkong" />清 空</el-button>
          </div>
        </div>
        <div class="con-row flex flexac flexjcsb pl">
          <el-button class="defaultbtn" type="primary" @click="handleRefresh"><i class="el-icon-refresh" :class="refresh?'goRefresh':''" />刷 新</el-button>
          <div class="m-r-25 flex">
            <el-button class="defaultbtn" type="primary" @click="handleAdd"><i class="el-icon-circle-plus-outline" />添加新角色</el-button>
            <el-button class="defaultbtn" type="primary" @click="handleExportExcel"><i class="iconfont icon-wenjiandaochu" />导出</el-button>
            <div class="pre m-l-10">
              <el-button class="defaultbtn pre" type="primary" @click="handleSenior('field')"><i class="iconfont icon-shezhi" />字段
              </el-button>
              <div class="selectUl" :class="seniorSet.field?'showSelectUl':'hideSelectUl'">

                <div v-for="(item,i) in tablehead" :key="i" class="li">
                  <el-checkbox v-model="item.isShow">{{ item.label }}</el-checkbox>
                </div>
              </div>
            </div>
            <div class="pre m-l-10">
              <el-button class="defaultbtn" type="primary" @click="handleSenior('sortable')"><i class="iconfont icon-shezhi" />排序</el-button>
              <div class="selectUl" :class="seniorSet.sortable ? 'showSelectUl' : 'hideSelectUl'">

                <div v-for="(item,i) in tablehead" v-if="item.isShow" :key="i" class="li">
                  <el-checkbox v-model="item.sortable">{{ item.label }}</el-checkbox>
                </div>
              </div>
            </div>
            <!-- <el-button class="defaultbtn" @click="handleExportExcel" type="primary"><i class="iconfont icon-shezhi"></i>固定</el-button> -->
          </div>
        </div>

        <el-tabs v-model="activeName" class="tabs" type="border-card" @tab-click="handleClick">
          <el-tab-pane v-for="items in options" :key="items.id" :label="items.value" :name="items.id">
            <!-- 功能角色 -->
            <div v-if="items.id === '0'">
              <el-table
                id="funcRoles"
                ref="funcRoles"
                class="con-table"
                type="expand"
                :data="funcRoles"
              >
                <!-- <el-table-column width="90" type="selection" label="全选" /> -->

                <template v-for="item in tablehead">
                  <el-table-column v-if="item.isShow" :key="item.index" :width="item.width" align="center" :sortable="item.sortable" :show-overflow-tooltip="true" :prop="item.prop" :label="item.label" />
                </template>

                <el-table-column prop="name" align="center" width="200" label="基本操作">
                  <template slot-scope="scope">
                    <el-button class="defaultbtn" type="primary" plain @click="handleEdit(scope.$index, scope.row)">
                      <i class="el-icon-edit" />编辑</el-button>
                    <el-button slot="reference" class="defaultbtn" type="danger" plain @click="handleDeleteBtn(scope.$index, scope.row)">
                      <i class="el-icon-delete" />删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <el-pagination
                class="paginationWrap flex"
                :current-page="paging.pageIndex"
                :page-sizes="[10]"
                :page-size="paging.pageSize"
                :pager-count="5"
                layout="total, sizes, prev, pager, next, jumper"
                :total="paging.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>

            <!-- 数据角色 -->
            <div v-else>
              <el-table
                id="dataRoles"
                ref="dataRoles"
                class="con-table"
                type="expand"
                :data="dataRoles"
              >
                <!-- <el-table-column width="90" type="selection" label="全选" /> -->

                <template v-for="item in tablehead">
                  <el-table-column v-if="item.isShow" :key="item.index" :width="item.width" align="center" :sortable="item.sortable" :show-overflow-tooltip="true" :prop="item.prop" :label="item.label" />
                </template>
              </el-table>

              <el-pagination
                class="paginationWrap flex"
                :current-page="pagings.pageIndex"
                :page-sizes="[10]"
                :page-size="pagings.pageSize"
                :pager-count="5"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pagings.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <RoleEdit v-model="visible" class="authorityRole" :datarole="editRole" :is-edit="isEdit" @handleRefresh="handleRefresh" @handleCloseDialog="handleCloseDialog" />
  </div>
</template>

<script>

import RoleEdit from './dialog/index'
import { findRoleList, deleteRole, findRoleDetail } from '@/api/baseInfo/authority/role'
import { showNotice, formatDateTime } from '@/utils/toolclass'

export default {
  components: { RoleEdit },
  props: {},
  data() {
    return {
      activeName: '0',
      options: [
        {
          id: '0',
          value: '功能角色'
        },
        {
          id: '1',
          value: '数据角色'
        }
      ],
      paging: {
        pageIndex: 1,
        pageSize: 10,
        pageSizeArr: [10],
        total: 0
      },
      pagings: {
        pageIndex: 1,
        pageSize: 10,
        pageSizeArr: [10],
        total: 0
      },
      param: {
        id: '',
        name: ''
      },
      tablehead: [
        {
          index: 0,
          prop: 'index',
          label: '序号',
          width: '120',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 1,
          prop: 'id',
          label: '角色ID',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 2,
          prop: 'name',
          label: '角色名称',
          sortable: false,
          fixed: true,
          isShow: true
        }
        // {
        //   index: 2,
        //   prop: 'orgName',
        //   label: '所属机构',
        //   sortable: false,
        //   fixed: true,
        //   isShow: true
        // }
      ],
      roleName: '',
      orgs: {
        orgId: '',
        orgName: '',
        range: ''
      },
      dataRoles: [],
      funcRoles: [],
      allRoles: [],
      visible: false,
      editRole: {},
      isEdit: false,
      refresh: false,
      seniorSet: {
        'field': false,
        'sortable': false
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getFuncRoles()
    this.getDataRoles()
    this.getAllRoles()
  },
  mounted() {
    this.$storage.set('upUrl', JSON.stringify({ 'path': '/authority/role/systemRole' }))
  },
  methods: {
    handleClick() {
      // console.log(this.activeName)
      if (this.activeName === '0') {
        this.getFuncRoles()
      } else {
        this.getDataRoles()
      }
    },
    handleExportExcel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/excel/Export2Excel')
        const tHeader = ['角色ID', '角色名称']
        const filterVal = ['id', 'name']
        const data = this.formatJson(filterVal, this.allRoles)
        export_json_to_excel(tHeader, data, '角色列表(' + formatDateTime().ymd) + ')'
      })
    },
    handleSenior(type) {
      if (type === 'field') {
        this.seniorSet.field = !this.seniorSet.field
      }
      if (type === 'sortable') {
        this.seniorSet.sortable = !this.seniorSet.sortable
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleRefresh() {
      this.refresh = true
      if (this.activeName === '0') {
        this.getFuncRoles()
      } else {
        this.getDataRoles()
      }
      setTimeout(() => {
        this.refresh = false
      }, 1200)
    },
    // 所有角色列表
    getAllRoles() {
      findRoleList('', '', '', 1, 100000).then((res) => {
        if (res.code === '000000') {
          // console.log('role', res)
          this.allRoles = res.data
        }
      })
    },
    // 功能角色
    getFuncRoles() {
      findRoleList(this.param.id, 0, this.param.name, this.paging.pageIndex, this.paging.pageSize).then((res) => {
        if (res.code === '000000') {
        // console.log('role', res)
          this.funcRoles = res.data.map((item, i) => {
            const items = {
              index: i + 1,
              id: item.id,
              name: item.name,
              version: item.version
            }
            return items
          })
          this.paging = {
            pageIndex: res.pager.pageIndex,
            pageSize: res.pager.pageSize,
            total: res.pager.totalSize
          }
        }
      })
    },
    // 数据角色
    getDataRoles() {
      findRoleList(this.param.id, 1, this.param.name, this.pagings.pageIndex, this.pagings.pageSize).then((res) => {
        if (res.code === '000000') {
          // console.log(res)
          this.dataRoles = res.data.map((item, i) => {
            const items = {
              index: i + 1,
              id: item.id,
              name: item.name,
              version: item.version
            }
            return items
          })
          this.pagings = {
            pageIndex: res.pager.pageIndex,
            pageSize: res.pager.pageSize,
            total: res.pager.totalSize
          }
        }
      })
    },
    handleDeleteBtn(index, row) {
      this.$alert('这个操作会删除和它相关联的所有数据,确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: action => {
          if (action === 'confirm') {
            this.handleDelete(row.id)
          }
        }
      })
    },
    handleDelete(id) {
      deleteRole(id).then(res => {
        if (res.code === '000000') {
          showNotice('success', '提示', '删除成功')
          this.getRoleList()
        }
      })
    },
    // 修改角色
    handleEdit(index, row) {
      this.visible = true
      this.isEdit = true
      // console.log(row)
      // 角色详情
      findRoleDetail(row.id).then(res => {
        if (res.code === '000000') {
          // console.log(res)
          res.data.dataRightList.map(item => {
            this.orgs = {
              orgId: item.orgId,
              orgName: item.orgName,
              range: item.range
            }
          })
          // console.log(this.orgs)
          this.editRole = {
            crtOpr: res.data.crtOpr, // 创建人ID
            isDataRole: res.data.isDataRole === null ? '功能权限' : res.data.isDataRole, // 是否数据权限（0：否；1：是）
            lstEdtOpr: res.data.lstEdtOpr, // 最后修改人ID
            id: res.data.id,
            name: res.data.name,
            version: res.data.version,
            orgId: this.orgs.orgId,
            orgName: this.orgs.orgName,
            range: this.orgs.range === 1 ? '本人' : this.orgs.range === 2 ? '本机构' : '本机构及其下级机构',
            type: res.data.type === 1 ? '普通角色' : '维保人员',
            sysRightList: res.data.sysRightList
          }
        }
      })
    },
    handleAdd() {
      this.visible = true
      this.isEdit = false
      this.editRole = {
        crtOpr: '', // 创建人ID
        isDataRole: '', // 是否数据权限（0：否；1：是）
        lstEdtOpr: '', // 最后修改人ID
        dataRightList: [], // 数据权限
        orgId: '', // 机构ID
        orgName: '', // 机构名称
        range: '本机构及其下级机构', // 范围（1：本人；2：本级；3：本级及下级机构；）
        tyep: '普通角色', // 角色类型
        id: 0, // ID
        name: '', // 角色名称
        sysRightList: [], // 平台功能权限
        displayType: 1, // 显示类型（1：可用且可显示；2：可显示但不可用；）
        menuRightList: [], // 菜单功能权限
        buttonRightList: [
          {
            buttonId: 9999,
            buttonName: '',
            displayType: 1,
            menuId: ''
          }
        ], // 按钮功能权限
        buttonId: '', // 按钮ID
        buttonName: '', // 按钮名
        menuId: '', // 菜单ID
        menuName: '', // 菜单名
        parentId: '', // 父级ID（查询)
        sort: '', // 排序号
        url: '', // URL
        sysId: '', // 系统ID
        sysName: '', // 系统名
        version: 1 // 版本号
      }
    },
    handleEmptySearch() {
      this.param.name = ''
      if (this.activeName === '0') {
        this.getFuncRoles()
      } else {
        this.getDataRoles()
      }
    },
    handleCloseDialog() {
      this.visible = !this.visible
    },
    handleSizeChange(val) {
      this.paging.pageSize = val
      if (this.activeName === '0') {
        this.getFuncRoles()
      } else {
        this.getDataRoles()
      }
    },
    handleCurrentChange(val) {
      if (this.activeName === '0') {
        this.paging.pageIndex = val
        this.getFuncRoles()
      } else {
        this.pagings.pageIndex = val
        this.getDataRoles()
      }
    }
  }
}
</script>
<style lang="scss">
@import '@/styles/public.scss';

.role {
  .role-main {
    .role-input {
      width: 240px;
    }
    .el-tabs--border-card>.el-tabs__content {
      padding: 15px 0 0 0;
    }
  }
}
</style>
